<template>
  <div class="dashboard">
    <!-- 页面头部LOGO -->
    <div class="dashboard-header">
      <div class="header-logo">
        <img src="/logo.png" alt="BY Logo" class="dashboard-logo" />
        <span class="header-title">宝洋后台管理系统</span>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" v-for="stat in stats" :key="stat.title">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.color }">
              <el-icon><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <span>卸货统计</span>
          </template>
          <div class="chart-container">
            <v-chart :option="unloadChartOption" style="height: 300px;" />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <span>数据分布</span>
          </template>
          <div class="chart-container">
            <v-chart :option="pieChartOption" style="height: 300px;" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格和快捷操作 -->
    <el-row :gutter="20" class="data-row">
      <el-col :span="14">
        <el-card class="unload-list-card">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <span>卸货列表</span>
                <span v-if="total > 0" class="data-count">(共 {{ total }} 条)</span>
              </div>
              <el-button 
                type="primary" 
                size="small" 
                :icon="Refresh"
                @click="refreshUnloadList"
                :loading="loading"
              >
                刷新
              </el-button>
            </div>
          </template>
          <div class="unload-list-container">
            <el-table 
              :data="unloadList" 
              stripe 
              v-loading="loading"
              :max-height="320"
              @scroll="handleTableScroll"
              :show-header="true"
              border
            >
              <el-table-column prop="index" label="序号" width="80" align="center">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="driverName" label="司机" min-width="150" />
              <el-table-column prop="containerNo" label="货物箱号" min-width="180" />
              <el-table-column prop="shippingStation" label="发货站" min-width="120" />
              <el-table-column prop="arrivalStation" label="到达站" min-width="120" />
              <el-table-column prop="unloadLocation" label="卸货地" min-width="120" />
              <el-table-column prop="unloadDate" label="卸货日期" min-width="120" />
              <el-table-column prop="projectName" label="货物品名" min-width="150" />
            </el-table>
            
            <!-- 加载更多按钮 -->
            <div v-if="hasMore" class="load-more">
              <el-button 
                type="primary" 
                :loading="loadingMore" 
                @click="loadMore"
                size="small"
              >
                {{ loadingMore ? '加载中...' : '加载更多' }}
              </el-button>
            </div>
            
            <!-- 无更多数据提示 -->
            <div v-else-if="unloadList.length > 0" class="no-more">
              <span>没有更多数据了</span>
            </div>
            
            <!-- 空数据提示 -->
            <div v-if="!loading && unloadList.length === 0" class="empty-data">
              <el-empty description="暂无卸货数据">
                <el-button type="primary" @click="refreshUnloadList">重新加载</el-button>
              </el-empty>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="10">
        <el-card class="quick-actions-card">
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="quick-actions">
            <el-button
              v-for="action in quickActions"
              :key="action.name"
              :type="action.type"
              :icon="action.icon"
              @click="handleQuickAction(action)"
              class="action-btn"
              size="large"
            >
              {{ action.name }}
            </el-button>
          </div>
          
          <el-divider />
          
          <div class="system-info">
            <h4>系统信息</h4>
            <div class="info-item">
              <span class="label">系统版本：</span>
              <span class="value">v1.0.0</span>
            </div>
            <div class="info-item">
              <span class="label">运行时间：</span>
              <span class="value">{{ systemUptime }}</span>
            </div>
            <div class="info-item">
              <span class="label">最后更新：</span>
              <span class="value">{{ lastUpdate }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getDashboardStats, getUnloadStats, getContainerDashboard, getUnloadList } from '@/api/dashboard'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'

// 注册 ECharts 组件
use([CanvasRenderer, LineChart, PieChart, GridComponent, TooltipComponent, LegendComponent])

const router = useRouter()

// 统计数据
const stats = ref([
  {
    title: '用户总数',
    value: '0',
    icon: 'User',
    color: '#409EFF'
  },
  {
    title: '角色数量',
    value: '0',
    icon: 'UserFilled',
    color: '#67C23A'
  },
  {
    title: '品名数量',
    value: '0',
    icon: 'Van',
    color: '#E6A23C'
  },
  {
    title: '小程序在线人数',
    value: '0',
    icon: 'View',
    color: '#F56C6C'
  }
])

// 卸货列表数据
const unloadList = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const total = ref(0)

// 快捷操作
const quickActions = ref([
  {
    name: '用户管理',
    icon: 'User',
    type: 'primary',
    path: '/user'
  },
  {
    name: '角色管理',
    icon: 'UserFilled',
    type: 'success',
    path: '/role'
  },
  {
    name: '品名管理',
    icon: 'Goods',
    type: 'warning',
    path: '/product'
  }
])

// 系统信息
const systemUptime = ref('')
const lastUpdate = ref('')
const loginTime = ref(null)

// 定时器ID存储
const timerIds = ref([])

// 卸货统计数据
const unloadData = ref([])
const unloadChartOption = ref({
  title: {
    text: '卸货数量',
    left: '2%',
    top: '50%',
    textStyle: {
      color: '#666',
      fontSize: 12
    },
    textAlign: 'center',
    textVerticalAlign: 'middle',
    rotate: 90
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: '#e6e6e6',
    borderWidth: 1,
    textStyle: {
      color: '#333'
    },
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: '#409EFF',
        width: 2,
        type: 'dashed'
      }
    }
  },
  grid: {
    left: '12%',
    right: '5%',
    bottom: '10%',
    top: '10%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    axisLine: {
      lineStyle: {
        color: '#e6e6e6'
      }
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: '#666',
      fontSize: 12
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: false
    },
    axisTick: {
      show: false
    },
    splitLine: {
      lineStyle: {
        color: '#f5f5f5',
        type: 'dashed'
      }
    },
    axisLabel: {
      color: '#666',
      fontSize: 12,
      show: true
    }
  },
  series: [
    {
      name: '卸货数量',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 3,
        color: '#409EFF'
      },
      itemStyle: {
        color: '#409EFF',
        borderWidth: 2,
        borderColor: '#fff'
      },
      areaStyle: {
        opacity: 0.3,
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(64, 158, 255, 0.6)'
            },
            {
              offset: 1,
              color: 'rgba(64, 158, 255, 0.1)'
            }
          ]
        }
      },
      emphasis: {
        focus: 'series',
        itemStyle: {
          color: '#409EFF',
          borderWidth: 3,
          borderColor: '#fff',
          shadowBlur: 10,
          shadowColor: 'rgba(64, 158, 255, 0.5)'
        }
      },
      data: []
    }
  ]
})

// 容器数据分布扇形图配置
const pieChartOption = ref({
  tooltip: {
    trigger: 'item',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: '#e6e6e6',
    borderWidth: 1,
    textStyle: {
      color: '#333'
    },
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    top: 'center',
    itemGap: 12,
    itemWidth: 12,
    itemHeight: 12,
    textStyle: {
      color: '#666',
      fontSize: 12
    },
    data: ['未到站', '已到站', '运输中', '今日卸货']
  },
  series: [
    {
      name: '容器状态',
      type: 'pie',
          radius: ['35%', '60%'],
    center: ['60%', '50%'],
      avoidLabelOverlap: false,
      label: {
        show: true,
        position: 'outside',
        formatter: '{b}\n{d}%',
        fontSize: 12,
        color: '#333',
        fontWeight: 'bold'
      },
      labelLine: {
        show: true,
        length: 15,
        length2: 10,
        lineStyle: {
          color: '#999',
          width: 1
        }
      },
      data: [
        { 
          value: 0, 
          name: '未到站', 
          itemStyle: { 
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 1, y2: 1,
              colorStops: [
                { offset: 0, color: '#FF6B6B' },
                { offset: 1, color: '#FF8E8E' }
              ]
            }
          } 
        },
        { 
          value: 0, 
          name: '已到站', 
          itemStyle: { 
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 1, y2: 1,
              colorStops: [
                { offset: 0, color: '#4ECDC4' },
                { offset: 1, color: '#6EDDD6' }
              ]
            }
          } 
        },
        { 
          value: 0, 
          name: '运输中', 
          itemStyle: { 
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 1, y2: 1,
              colorStops: [
                { offset: 0, color: '#45B7D1' },
                { offset: 1, color: '#67C7DB' }
              ]
            }
          } 
        },
        { 
          value: 0, 
          name: '今日卸货', 
          itemStyle: { 
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 1, y2: 1,
              colorStops: [
                { offset: 0, color: '#96CEB4' },
                { offset: 1, color: '#B8DEC6' }
              ]
            }
          } 
        }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 20,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        }
      }
    }
  ]
})

// 处理快捷操作
const handleQuickAction = (action) => {
  if (action.path) {
    router.push(action.path)
  } else {
    ElMessage.info(`点击了${action.name}`)
  }
}

// 获取统计数据
const getStats = async () => {
  try {
    const response = await getDashboardStats()
    console.log('统计数据响应:', response)
    
    // 根据接口返回的数据更新统计信息
    if (response) {
      // 根据实际接口返回的数据结构调整
      stats.value[0].value = response.userCount || '0'
      stats.value[1].value = response.roleCount || '0'
      stats.value[2].value = response.productNameCount || '0'
      stats.value[3].value = response.onlineCount || '0'
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取卸货统计数据
const getUnloadStatsData = async () => {
  try {
    const response = await getUnloadStats()
    console.log('卸货统计数据响应:', response)
    
    if (response && Array.isArray(response)) {
      unloadData.value = response
      
      // 更新图表数据
      const dates = response.map(item => item.date)
      const counts = response.map(item => item.count)
      
      unloadChartOption.value.xAxis.data = dates
      unloadChartOption.value.series[0].data = counts
    }
  } catch (error) {
    console.error('获取卸货统计数据失败:', error)
    ElMessage.error('获取卸货统计数据失败')
  }
}

// 获取容器数据看板数据
const getContainerDashboardData = async () => {
  try {
    const response = await getContainerDashboard()
    console.log('容器数据看板响应:', response)
    
    if (response) {
      // 更新扇形图数据
      pieChartOption.value.series[0].data = [
        { 
          value: response.notArrived || 0, 
          name: '未到站', 
          itemStyle: { color: '#FF6B6B' } 
        },
        { 
          value: response.arrived || 0, 
          name: '已到站', 
          itemStyle: { color: '#4ECDC4' } 
        },
        { 
          value: response.inTransport || 0, 
          name: '运输中', 
          itemStyle: { color: '#45B7D1' } 
        },
        { 
          value: response.unloadToday || 0, 
          name: '今日卸货', 
          itemStyle: { color: '#96CEB4' } 
        }
      ]
    }
  } catch (error) {
    console.error('获取容器数据看板失败:', error)
    ElMessage.error('获取容器数据看板失败')
  }
}

// 获取卸货列表数据
const getUnloadListData = async (isLoadMore = false) => {
  if (isLoadMore) {
    loadingMore.value = true
  } else {
    loading.value = true
  }
  
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    const response = await getUnloadList(params)
    console.log('卸货列表响应:', response)
    
    if (response && response.records) {
      // 处理数据，映射字段
      const processedData = response.records.map(item => ({
        id: item.id,
        driverName: item.driverName,
        containerNo: item.boxNo,
        unloadLocation: item.unloadPoint,
        unloadDate: item.unloadingDate,
        shippingStation: item.shippingStation,
        arrivalStation: item.arrivalStation,
        loadingWeight: item.loadingWeight,
        unloadingWeight: item.unloadingWeight,
        containerLot: item.containerLot,
        projectName: item.projectName
      }))
      
      if (isLoadMore) {
        // 加载更多时追加数据
        unloadList.value.push(...processedData)
      } else {
        // 首次加载时替换数据
        unloadList.value = processedData
      }
      
      total.value = response.total || 0
      hasMore.value = unloadList.value.length < total.value
    }
  } catch (error) {
    console.error('获取卸货列表失败:', error)
    ElMessage.error('获取卸货列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多数据
const loadMore = () => {
  if (!hasMore.value || loadingMore.value) return
  
  currentPage.value++
  getUnloadListData(true)
}

// 表格滚动处理（自动加载更多）
const handleTableScroll = (e) => {
  const { scrollTop, scrollHeight, clientHeight } = e.target
  // 当滚动到底部时自动加载更多
  if (scrollHeight - scrollTop - clientHeight < 100 && hasMore.value && !loadingMore.value) {
    loadMore()
  }
}

// 刷新卸货列表
const refreshUnloadList = () => {
  currentPage.value = 1
  unloadList.value = []
  hasMore.value = true
  getUnloadListData()
}

// 计算系统运行时间
const calculateUptime = () => {
  if (!loginTime.value) {
    systemUptime.value = '0天 0小时 0分钟'
    return
  }
  
  const now = new Date()
  const diff = now - loginTime.value
  
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  
  systemUptime.value = `${days}天 ${hours}小时 ${minutes}分钟`
}

// 清理定时器的函数
const clearAllTimers = () => {
  console.log('清理dashboard定时器')
  timerIds.value.forEach(timerId => {
    clearInterval(timerId)
  })
  timerIds.value = []
}

// 监听退出登录事件
const handleLogout = () => {
  clearAllTimers()
}

// 初始化
onMounted(() => {
  // 添加退出登录事件监听
  window.addEventListener('logout', handleLogout)
  
  // 从localStorage获取登录时间，如果没有则设置为当前时间
  const storedLoginTime = localStorage.getItem('loginTime')
  if (storedLoginTime) {
    loginTime.value = new Date(storedLoginTime)
  } else {
    loginTime.value = new Date()
    localStorage.setItem('loginTime', loginTime.value.toISOString())
  }
  
  calculateUptime()
  lastUpdate.value = new Date().toLocaleString()
  
  // 获取统计数据
  getStats()
  
  // 获取卸货统计数据
  getUnloadStatsData()
  
  // 获取容器数据看板数据
  getContainerDashboardData()
  
  // 获取卸货列表数据
  getUnloadListData()
  
  // 每分钟更新一次运行时间
  const uptimeTimer = setInterval(calculateUptime, 60000)
  timerIds.value.push(uptimeTimer)
  
  // 每分钟更新一次统计数据
  const statsTimer = setInterval(getStats, 60000)
  timerIds.value.push(statsTimer)
  
  // 每5分钟更新一次卸货统计数据
  const unloadStatsTimer = setInterval(getUnloadStatsData, 300000)
  timerIds.value.push(unloadStatsTimer)
  
  // 每5分钟更新一次容器数据看板数据
  const containerDashboardTimer = setInterval(getContainerDashboardData, 300000)
  timerIds.value.push(containerDashboardTimer)
})

// 组件卸载时清理定时器和事件监听
onUnmounted(() => {
  clearAllTimers()
  window.removeEventListener('logout', handleLogout)
})
</script>

<style lang="scss" scoped>
.dashboard {
  background-color: #f8fafc;
  min-height: 100vh;
  padding: 20px;
  .dashboard-header {
    margin-bottom: 20px;
    padding: 20px;
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    
          .header-logo {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .dashboard-logo {
          width: 40px;
          height: 40px;
          border-radius: 6px;
        }
        
                 .header-title {
           color: #2c3e50;
           font-size: 20px;
           font-weight: 600;
         }
      }
  }
  
  .stats-row {
    margin-bottom: 16px;
    
    .stat-card {
      border-radius: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      
      &:hover {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
      }
      
      .stat-content {
        display: flex;
        align-items: center;
        
        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          
          .el-icon {
            font-size: 24px;
            color: #fff;
          }
        }
        
        .stat-info {
          flex: 1;
          
          .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: #333;
            margin-bottom: 4px;
            line-height: 1.2;
          }
          
          .stat-title {
            font-size: 14px;
            color: #666;
            margin-bottom: 4px;
            font-weight: 500;
          }
        }
      }
    }
  }
  
  .chart-row {
    margin-bottom: 16px;
    
          .chart-card {
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;
        
        &:hover {
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
        }
        
        .chart-placeholder {
          height: 300px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #999;
          
          p {
            margin-top: 16px;
            font-size: 14px;
          }
        }
        
        .chart-container {
          height: 300px;
          border-radius: 8px;
          overflow: hidden;
        }
      }
  }
  
  .data-row {
    margin-bottom: 0;
    .unload-list-card {
      height: 450px;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-left {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .data-count {
            color: #666;
            font-size: 14px;
          }
        }
      }
      
      .unload-list-container {
        height: calc(100% - 60px); // 减去卡片头部的高度
        display: flex;
        flex-direction: column;
        
        .el-table {
          flex: 1;
          min-height: 200px;
        }
        
        .load-more {
          text-align: center;
          padding: 12px 0;
          border-top: 1px solid #f0f0f0;
          background: #fafafa;
        }
        
        .no-more {
          text-align: center;
          padding: 12px 0;
          color: #999;
          font-size: 14px;
          border-top: 1px solid #f0f0f0;
          background: #fafafa;
        }
        
        .empty-data {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%;
          flex: 1;
        }
      }
    }
    
    .quick-actions-card {
      height: 450px;
      
      .quick-actions {
        display: flex;
        flex-direction: column;
        gap: 12px;
        margin-bottom: 20px;
        width: 100%;
        
        .action-btn {
          height: 48px;
          width: 100%;
          font-size: 15px;
          font-weight: 500;
          border-radius: 8px;
          transition: all 0.3s ease;
          margin: 0;
          
          &:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
      
      .system-info {
        h4 {
          margin-bottom: 12px;
          color: #333;
          font-size: 16px;
        }
        
        .info-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 6px;
          padding: 4px 0;
          
          .label {
            color: #666;
            font-size: 14px;
          }
          
          .value {
            color: #333;
            font-weight: 500;
            font-size: 14px;
          }
        }
      }
    }
  }
}
</style> 